<?php

class UsersController extends Controller {
    public $layout = 'contents';
    const PAGE_SIZE = 16;

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',  // allow all users to perform 'list' and 'show' actions
                'actions'=>array('index', 'create', 'changeStatus', 'changePassword'),
                'users'=>array('@'),
            ),
//            array('allow', // allow authenticated user to perform 'create' and 'update' actions
//                'actions'=>array('create','update'),
//                'users'=>array('@'),
//            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    // change status
    public function actionChangeStatus() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = User::model()->findByPk($id);
            switch ($model->status) {
                case 0:
                    $status = 1; break;
                case 1:
                    $status = 0; break;
            }
            $model->status = $status;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->statusIconFormat;
        }
    }

    // change user password
    public function actionChangePassword() {
        $model = $this->loadUser();
        if (isset($_POST['User'])) {
            $model->password = md5($_POST['User']['password']);
            if ($model->save()) {
                $this->redirect(array('index'));
            }
        }
        $this->render('changepassword', array('model' => $model));
    }

    /**
     * Shows a particular model.
     */
    public function actionShow() {
        $this->render('show', array('model' => $this->loadUser()));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
    public function actionCreate() {
        $model = new User;
        $msg = '注意：新增系统管理帐号不能和已有帐号同名。';
        if (isset($_POST['User'])) {
            $username = strtolower(trim($_POST['User']['username']));
            $password = trim($_POST['User']['username']);
            if ($username == '' || $password == '') {
                $msg = '请输入用户名和密码';
            } else {
                $user = User::model()->find('LOWER(username) = ?', array($username));
                if ($user->id) {
                    $msg = "提示：{$username} 帐号已经存在，请使用其他的帐号。";
                } else {
                    $model->username = $username;
                    $model->password = md5($_POST['User']['password']);
                    if ($model->save()) {
                        $this->redirect(array('index'));
                    }
                }
            }
        }
        $this->render('create', array(
            'model' => $model,
            'msg' => $msg
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            $will_deleting = (array)Yii::app()->request->getPost('delete');
            foreach ($will_deleting as $user_id) {
                User::model()->findByPk($user_id)->delete();
            }

            return $this->redirect(array('index'));
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
//        $this->processAdminCommand();

        $criteria = new CDbCriteria;

        $pages = new CPagination(User::model()->count($criteria));
        $pages->pageSize = self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort = new CSort('User');
        $sort->applyOrder($criteria);

        $models = User::model()->with('group')->findAll($criteria);

        $this->render('index', array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadUser($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=User::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadUser($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
